<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>添加</title>
    <link rel="stylesheet" href="${ctx}/static/js/layui/css/layui.css">
    <link rel="stylesheet" href="${ctx}/static/js/formSelects-v4.css">
    <style type="text/css">
        .msg {
            color: red !important;
        }
    </style>
</head>
<body>
<div style="padding: 10px;">
    <input type="hidden" id="temp">
    <form class="layui-form" action="" id="product-from">
        <input name="id" value="${commodity.id }" type="hidden">
        <div class="layui-form-item">
            <label class="layui-form-label">商品名称</label>
            <div class="layui-input-inline">
                <input type="text" name="name" required value="${commodity.name }"
                       lay-verify="required" placeholder="请输入商品名称" autocomplete="off"
                       class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">价格</label>
            <div class="layui-input-inline">
                <input type="text" name="price" required value="${commodity.price }"
                       lay-verify="required" placeholder="请输入价格" autocomplete="off"
                       class="layui-input">
            </div>
            <div class="layui-form-mid layui-word-aux msg"></div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">图片</label>
            <div class="layui-input-inline">
                <button type="button" class="layui-btn" id="test1">
                    <i class="layui-icon">&#xe67c;</i>上传图片
                </button>
            </div>
            <input type="hidden" name="img" id="img" value="${commodity.img}">
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"></label>
            <img class="layui-upload-img" width="50px" id="demo1" src="${ctx}/user/getImage?name=${commodity.img}">
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">销量</label>
            <div class="layui-input-inline">
                <input type="text" name="sales" required value="${commodity.sales}"
                       lay-verify="required" placeholder="请输入销量" autocomplete="off"
                       class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">库存</label>
            <div class="layui-input-inline">
                <input type="text" name="stocks" required value="${commodity.stocks}"
                       lay-verify="required" placeholder="请输入库存" autocomplete="off" +
                       class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">商品类别</label>
            <div class="layui-input-block">
                <select name="comtypeName" lay-verify="required" xm-select="comtypeName">
                    <!-- <option value=""></option> -->
                    <c:forEach items="${comtype}" var="comtype">
                        <option value="${comtype.id }">${comtype.name }</option>
                    </c:forEach>
                </select>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">商品品牌</label>
            <div class="layui-input-block">
                <select name="brandId" xm-select="brandId" xm-select-radio>
                    <!-- <option value=""></option> -->
                    <c:forEach items="${brands }" var="brand">
                        <option value="${brand.id }">${brand.markname }</option>
                    </c:forEach>
                </select>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">商品详情</label>
            <div class="layui-input-block">
                <button type="button" class="layui-btn bt-clear" data-name="dimg" id="test1">
                    <i class="layui-icon">&#xe67c;</i>清除
                </button>
                <button type="button" class="layui-btn bt-upload" data-name="dimg" id="test1">
                    <i class="layui-icon">&#xe67c;</i>上传图片
                </button>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"></label>
            <div id="dimg">

            </div>
        </div>

        <input type='hidden' name='dimg'>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>
    <script src="${ctx}/static/js/layui/layui.js"></script>
    <script>
        layui.config({
            base: '${ctx}/static/js/' //此处路径请自行处理, 可以使用绝对路径
        }).extend({
            formSelects: 'formSelects-v4.min'
        });
        layui.use(['form', 'upload', 'formSelects'], function () {
            var form = layui.form;
            var upload = layui.upload;
            var $ = layui.$;
            var formSelects = layui.formSelects;

            //监听提交
            form.on('submit(formDemo)', function (data) {
                $('.headMsg').text("");
                if (!$('#img').val()) {
                    $('.headMsg').text("图片不能为空");
                    return false;
                }

                //$.post一般来说需要3个参数：url，参数，回调函数
                $.post('${ctx}/commodity/update', data.field, function (e) {
                    if (e == "") {
                        parent.layui.table.reload("demo");
                        parent.layer.msg('修改成功', {icon: 1});		//高用父窗口中的layer来提示，这样关闭弹出窗后提示不会立马关闭
                        var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                        parent.layer.close(index); //再执行关闭
                    } else {
                        alert("失败");
                    }
                })
                return false;
            });


            //上传头像
            var uploadInst = upload.render({
                elem: '#test1' //绑定元素
                , url: '${ctx}/upload' //上传接口
                , before: function (obj) {
                    //预读本地文件示例，不支持ie8
                    obj.preview(function (index, file, result) {
                        $('#demo1').attr('src', result); //图片链接（base64）
                    });
                }
                , done: function (res) {
                    //上传完毕回调
                    console.log(res);
                    $('#img').val(res.name);
                },
                error: function (e) {
                    //请求异常回调
                    console.log(e);
                }
            });

            //显示该商品的详细信息
            var dimgs = '${comimgsString}';
            var dimgsarr = dimgs.split(",");
            for (var i in dimgsarr) {
                console.log(dimgsarr[i]);
                var dimg = $("#dimg");
                dimg.append("<img style='padding-right: 10px;' width='50px' src='${ctx}/user/getImage?name=" + dimgsarr[i] + "'/>");
            }
            //将值传入商品详情输入框
            $('input[name="dimg"]').val(dimgs);


            $('.bt-upload').on('click', function () {
                var file_form = $('<form method="post" enctype="multipart/form-data"></form>');
                var file_bt = '<input style="display: none" type="file" name="file">';
                if ($(this).next().length <= 0) {
                    $(file_form).append(file_bt);
                    $($(this)).after(file_form);
                }
                $(this).next().children("input").click();
                return false;
            })

            $('body').on('change', 'input[type=file]', function (e) {
                var bt_name = $($(this).parent().prev()).attr("data-name");
                $('#temp').val(bt_name);
                $.ajax({
                    url: '${ctx}/upload',
                    type: 'POST',
                    cache: false,
                    data: new FormData($(this).parent()[0]),
                    processData: false,
                    contentType: false,
                    dataType: "json",
                    beforeSend: function () {
                        uploading = true;
                    },
                    success: function (data) {
                        console.log(data);
                        var bn = $('#temp').val();
                        if (bn == "dimg") {
                            var v = $('input[name="' + bn + '"]').val();
                            $('input[name="' + bn + '"]').remove();
                            $('#' + bn).append('<img alt="" style="padding-right: 10px;" src="' + "${ctx}/user/getImage?name=" + data.name + '" width="50px">');
                            if (v != "" && v != undefined) {
                                v = v + ",";
                            } else {
                                v = "";
                            }
                            v = v + data.name;
                            $('.layui-form').prepend("<input type='hidden' name='" + bn + "' value='" + v + "'>")
                        } else {
                            $('input[name="' + bn + '"]').remove();
                            $('.layui-form').prepend("<input type='hidden' name='" + bn + "' value='" + data.name + "'>")
                            $('#' + bn).attr("src", "${ctx}/user/getImage?name=" + data.name);
                        }
                    }
                });
            })

            $('.bt-clear').on('click', function () {
                var bt = $(this).attr("data-name");
                $('input[name="' + bt + '"]').val("");
                $('#' + bt).empty();
                return false;
            })

            //勾选上已选择的商品类别
            var data = '${goodstypeIDs}';
            var comtypes = JSON.parse(data);
            var choiseComtype = [];
            for (var i in comtypes) {
                choiseComtype[i] = comtypes[i].typeId;
            }
            console.log(choiseComtype);
            formSelects.value('comtypeName', choiseComtype);

            //勾选上已选择的商品品牌
            var data = '${commodity.brandId}';
            var choiseComtype = [];
            choiseComtype[0] = data;
            console.log(choiseComtype);
            formSelects.value('brandId', choiseComtype);
        });
    </script>
</div>
</body>
</html>